<template>
	<view class="page-wrapper" 
		@touchstart="handleTouchStart"
		@touchmove="handleTouchMove" 
		@touchend="handleTouchEnd">
		<view v-if="isLoading" class="skeleton-container">
			<view class="skeleton-header">
				<view class="skeleton-date"></view>
				<view class="skeleton-search"></view>
			</view>
			<view class="skeleton-main-title"></view>
			<view class="skeleton-category-flow">
				<view class="skeleton-category-chip" v-for="i in 5" :key="i"></view>
			</view>
			<view class="skeleton-focus-news"></view>
			<view class="skeleton-featured-section">
				<view class="skeleton-section-title"></view>
				<view class="skeleton-featured-cards">
					<view class="skeleton-featured-card" v-for="i in 3" :key="i"></view>
				</view>
			</view>
			<view class="skeleton-news-section">
				<view class="skeleton-section-title"></view>
				<view class="skeleton-news-list">
					<view class="skeleton-news-item" v-for="i in 3" :key="i"></view>
				</view>
			</view>
		</view>
		<view v-else>
			<view class="fixed-header">
				<view class="status-bar-height"></view>
				<view class="header">
					<view class="header-left">
						<text class="date-text">{{ formattedDate }}</text>
					</view>
					<view class="header-right">
						<view class="search-btn" @tap="openSearch">
							<uni-icons type="search" size="22" color="#333"></uni-icons>
						</view>
					</view>
				</view>
				<view class="main-title-area">
					<text class="main-title">TODAY</text>
					<text class="sub-title">最新热门资讯</text>
				</view>
				<scroll-view class="category-flow" scroll-x :show-scrollbar="false">
					<view 
						class="category-chip" 
						:class="{ active: currentCategory === index }"
						v-for="(item, index) in categories" 
						:key="index"
						@tap="selectCategory(index)"
					>
						{{ item.name }}
					</view>
				</scroll-view>
				
				<!-- 滑动提示 -->
				<view class="swipe-hint" v-if="showSwipeHint">
					<text class="hint-text">👈 左右滑动切换页面 👉</text>
				</view>
			</view>
			<scroll-view
				class="content-scroll"
				scroll-y
				refresher-enabled
				@refresherrefresh="onRefresh"
				:refresher-triggered="isRefreshing"
				@scrolltolower="loadMore"
				:show-scrollbar="false"
			>
				<view class="focus-news" v-if="focusNews">
					<view class="focus-card" @tap="viewNews(focusNews)">
						<image class="focus-image" :src="focusNews.cover" mode="aspectFill"></image>
						<view class="focus-overlay"></view>
						<view class="focus-content">
							<view class="focus-title">{{ focusNews.title }}</view>
							<view class="focus-meta">
								<text>{{ focusNews.source }}</text>
								<text class="dot">•</text>
								<text>{{ formatTime(focusNews.create_time) }}</text>
							</view>
						</view>
					</view>
				</view>
				
				<view class="featured-section" v-if="featuredNews && featuredNews.length">
					<view class="section-title">
						<text class="title-text">推荐</text>
						<view class="title-line"></view>
					</view>
					
					<scroll-view class="featured-scroll" scroll-x :show-scrollbar="false">
						<view class="featured-card" v-for="(item, index) in featuredNews" :key="index" @tap="viewNews(item)">
							<image class="featured-image" :src="item.cover" mode="aspectFill"></image>
							<view class="featured-title">{{ item.title }}</view>
							<view class="featured-source">{{ item.source }}</view>
						</view>
					</scroll-view>
				</view>
				<view class="news-section">
					<view class="section-title">
						<text class="title-text">最新</text>
						<view class="title-line"></view>
					</view>
					
					<view class="news-list">
						<view class="news-item" v-for="(item, index) in newsList" :key="index" @tap="viewNews(item)">
							<view class="news-content">
								<view class="news-top">
									<view class="news-tag">{{ item.tag }}</view>
									<text class="news-time">{{ formatTime(item.create_time) }}</text>
								</view>
								<view class="news-title">{{ item.title }}</view>
								<view class="news-source">
									<view class="source-avatar">
										<image :src="item.source_icon ? item.source_icon : '/static/logo.png'" mode="aspectFill"></image>
									</view>
									<text>{{ item.user.username }}</text>
								</view>
							</view>
							<view class="news-image" v-if="item.cover">
								<image :src="item.cover" mode="aspectFill"></image>
							</view>
						</view>
					</view>
					<view class="load-more" v-if="loadMoreStatus === 'loading'">
						<view class="loading-spinner"></view>
						<text>加载中...</text>
					</view>
					<view class="load-more" v-else-if="loadMoreStatus === 'noMore'">
						<text>没有更多内容</text>
					</view>
				</view>
			</scroll-view>
		</view>
		<view class="fab-button" @tap="scrollToTop">
			<uni-icons type="top" size="24" color="#fff"></uni-icons>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getNewsList, getFeaturedNews, getFocusNews } from '@/api/post'

// 原有数据
const formattedDate = ref('')
const isRefreshing = ref(false)
const isLoading = ref(true)
const currentCategory = ref(0)
const loadMoreStatus = ref('more')
const categories = ref([
    { name: '推荐' },
    { name: '科技' },
    { name: '娱乐' },
    { name: '体育' },
    { name: '财经' }
])
const focusNews = ref(null)
const featuredNews = ref([])
const newsList = ref([])
const pageSize = ref(10)
const pageIndex = ref(1)

// 滑动相关数据
const showSwipeHint = ref(true)
const startX = ref(0)
const startY = ref(0)
const startTime = ref(0)

// TabBar页面路径配置
const tabPages = [
	'/pages/index/index',        // 0: 打听事
	'/pages/score/index',  // 1: 评分
	'/pages/schedule/index', // 2: 换班
	'/pages/profile/index'     // 3: 我的
]

// 滑动手势处理
const handleTouchStart = (e) => {
	const touch = e.touches[0]
	startX.value = touch.clientX || touch.pageX
	startY.value = touch.clientY || touch.pageY
	startTime.value = Date.now()
}

const handleTouchMove = (e) => {
	// 在滑动过程中什么都不做，避免影响滚动
}

const handleTouchEnd = (e) => {
	const touch = e.changedTouches[0]
	const endX = touch.clientX || touch.pageX
	const endY = touch.clientY || touch.pageY
	
	const deltaX = endX - startX.value
	const deltaY = endY - startY.value
	const duration = Date.now() - startTime.value
	
	// 判断是否为水平滑动
	if (Math.abs(deltaY) > Math.abs(deltaX) || Math.abs(deltaX) < 50) {
		return
	}
	
	// 判断滑动速度和距离
	const velocity = Math.abs(deltaX) / duration
	const isValidSwipe = Math.abs(deltaX) > 80 || (velocity > 0.3 && Math.abs(deltaX) > 30)
	
	if (!isValidSwipe) return
	
	// 隐藏提示
	showSwipeHint.value = false
	
	// 当前是打听事页面(index=0)
	const currentIndex = 0
	let targetIndex = currentIndex
	
	if (deltaX > 0) {
		// 向右滑动，切换到上一个页面
		targetIndex = currentIndex > 0 ? currentIndex - 1 : tabPages.length - 1
	} else {
		// 向左滑动，切换到下一个页面  
		targetIndex = currentIndex < tabPages.length - 1 ? currentIndex + 1 : 0
	}
	
	// 执行页面切换
	uni.switchTab({
		url: tabPages[targetIndex],
		success: () => {
			uni.showToast({
				title: `切换到 ${getPageName(targetIndex)}`,
				icon: 'none',
				duration: 1000
			})
		}
	})
}

const getPageName = (index) => {
	const names = ['打听事', '评分', '换班', '我的']
	return names[index] || '未知页面'
}

// 原有方法保持不变
const setFormattedDate = () => {
    const now = new Date()
    const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    
    const day = days[now.getDay()]
    const date = now.getDate()
    const month = months[now.getMonth()]
    
    formattedDate.value = `${day}, ${month} ${date}`
}
const initData = async () => {
    try {
        isLoading.value = true
        // // 获取焦点新闻
        // const focusRes = await getFocusNews()
        // focusNews.value = focusRes.data
        //
        // // 获取推荐新闻
        // const featuredRes = await getFeaturedNews()
        // featuredNews.value = featuredRes.data

        // 获取新闻列表
        const newsRes = await getNewsList({
            page: pageIndex.value,
            pageSize: pageSize.value,
            category: categories.value[currentCategory.value].name
        })
        newsList.value = newsRes.data.list
    } catch (error) {
        console.error('获取数据失败:', error)
        uni.showToast({
            title: '获取数据失败',
            icon: 'none'
        })
    } finally {
        isLoading.value = false
    }
}
const formatTime = (timestamp) => {
    const now = Date.now()
    const diff = now - timestamp
    const hours = Math.floor(diff / (1000 * 60 * 60))
    return hours > 0 ? `${hours}小时前` : '刚刚'
}

const selectCategory = async (index) => {
    currentCategory.value = index
    pageIndex.value = 1
    try {
        const res = await getNewsList({
            page: pageIndex.value,
            pageSize: pageSize.value,
            category: categories.value[index].name
        })
        newsList.value = res.data.list
    } catch (error) {
        console.error('切换分类失败:', error)
        uni.showToast({
            title: '切换分类失败',
            icon: 'none'
        })
    }
}
const onRefresh = async () => {
    isRefreshing.value = true
    pageIndex.value = 1
    try {
        await initData()
    } catch (error) {
        console.error('刷新失败:', error)
    } finally {
        isRefreshing.value = false
    }
}
const loadMore = async () => {
    if (loadMoreStatus.value !== 'more') return
    
    loadMoreStatus.value = 'loading'
    
    try {
        const res = await getNewsList({
            page: pageIndex.value + 1,
            pageSize: pageSize.value,
            category: categories.value[currentCategory.value].name
        })
        
        if (res.data.list && res.data.list.length > 0) {
            newsList.value = [...newsList.value, ...res.data.list]
            pageIndex.value++
            loadMoreStatus.value = 'more'
        } else {
            loadMoreStatus.value = 'noMore'
        }
    } catch (error) {
        console.error('加载更多失败:', error)
        uni.showToast({
            title: '加载更多失败',
            icon: 'none'
        })
        loadMoreStatus.value = 'more'
    }
}

const viewNews = (item) => {
    const newsId = item && item._id 
        ? item._id 
        : `news_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    try {
        uni.navigateTo({
            url: `/pages/index/detail/detail?id=${newsId}`,
            fail: (err) => {
                console.error('Navigation error:', err);
                uni.showToast({
                    title: '无法打开详情页',
                    icon: 'none'
                });
            }
        });
    } catch (error) {
        console.error('Navigation catch error:', error);
        uni.showToast({
            title: '导航出错',
            icon: 'none'
        });
    }
}
const openSearch = () => {
    uni.showToast({
        title: '打开搜索页面',
        icon: 'none'
    })
}

const scrollToTop = () => {
    uni.pageScrollTo({
        scrollTop: 0,
        duration: 300
    })
}
onMounted(() => {
    setFormattedDate()
    initData()
})
</script>

<style>
	.skeleton-container {
		padding: 30rpx;
	}
	.skeleton-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 20rpx;
	}
	.skeleton-date {
		width: 150rpx;
		height: 30rpx;
		background-color: #f0f0f0;
		border-radius: 10rpx;
	}
	.skeleton-search {
		width: 50rpx;
		height: 50rpx;
		background-color: #f0f0f0;
		border-radius: 50%;
	}
	.skeleton-main-title {
		width: 200rpx;
		height: 50rpx;
		background-color: #f0f0f0;
		margin-bottom: 20rpx;
		border-radius: 10rpx;
	}
	.skeleton-category-flow {
		display: flex;
		margin-bottom: 20rpx;
	}
	.skeleton-category-chip {
		width: 80rpx;
		height: 40rpx;
		background-color: #f0f0f0;
		margin-right: 10rpx;
		border-radius: 20rpx;
	}
	.skeleton-focus-news {
		width: 100%;
		height: 500rpx;
		background-color: #f0f0f0;
		border-radius: 30rpx;
		margin-bottom: 20rpx;
	}
	.skeleton-featured-section {
		margin-bottom: 20rpx;
	}
	.skeleton-section-title {
		width: 150rpx;
		height: 40rpx;
		background-color: #f0f0f0;
		margin-bottom: 10rpx;
		border-radius: 10rpx;
	}
	.skeleton-featured-cards {
		display: flex;
	}
	.skeleton-featured-card {
		width: 200rpx;
		height: 250rpx;
		background-color: #f0f0f0;
		margin-right: 10rpx;
		border-radius: 20rpx;
	}
	.skeleton-news-section {
		margin-bottom: 20rpx;
	}
	.skeleton-news-item {
		width: 100%;
		height: 150rpx;
		background-color: #f0f0f0;
		margin-bottom: 10rpx;
		border-radius: 20rpx;
	}

	.fixed-header {
		position: fixed;
		top: 0;
		left: 0;
		width: 100vw;
		z-index: 100;
		background: #fff;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.03);
	}
	
	.content-scroll {
		margin-top: 500rpx;
		height: calc(100vh  - var(--status-bar-height));
	}
	
	.status-bar-height {
		height: var(--status-bar-height);
		width: 100%;
	}
	
	.header {
		padding: 20rpx 40rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.header-left {
		display: flex;
		align-items: center;
	}
	
	.date-text {
		font-size: 28rpx;
		color: #666;
	}
	
	.header-right {
		display: flex;
		align-items: center;
	}
	
	.search-btn {
		width: 70rpx;
		height: 70rpx;
		border-radius: 50%;
		background-color: #fff;
		display: flex;
		justify-content: center;
		align-items: center;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
	}
	
	.main-title-area {
		padding: 20rpx 40rpx 40rpx;
	}
	
	.main-title {
		font-size: 56rpx;
		font-weight: 800;
		color: #333;
		letter-spacing: 2rpx;
	}
	
	.sub-title {
		font-size: 30rpx;
		color: #888;
		margin-top: 8rpx;
		display: block;
	}
	
	.category-flow {
		white-space: nowrap;
		padding: 0 30rpx 30rpx;
	}
	
	.category-chip {
		display: inline-block;
		padding: 15rpx 30rpx;
		margin: 0 10rpx;
		background-color: #eef0f2;
		border-radius: 30rpx;
		font-size: 26rpx;
		color: #666;
		transition: all 0.3s;
	}
	
	.category-chip.active {
		background-color: #333;
		color: #fff;
	}
	
	/* 滑动提示样式 */
	.swipe-hint {
		padding: 15rpx 40rpx;
		background: linear-gradient(135deg, #6c5ce7, #a29bfe);
		text-align: center;
		animation: fadeInOut 3s ease-in-out;
	}
	
	.hint-text {
		font-size: 24rpx;
		color: #fff;
		opacity: 0.9;
	}
	
	@keyframes fadeInOut {
		0%, 100% { opacity: 0; transform: translateY(-10rpx); }
		20%, 80% { opacity: 1; transform: translateY(0); }
	}
	
	.focus-news {
		padding: 0 30rpx;
		margin-bottom: 40rpx;
	}
	
	.focus-card {
		position: relative;
		width: 100%;
		height: 500rpx;
		border-radius: 30rpx;
		overflow: hidden;
	}
	
	.focus-image {
		width: 100%;
		height: 100%;
	}
	
	.focus-overlay {
		position: absolute;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 70%;
		background: linear-gradient(to top, rgba(0,0,0,0.8), transparent);
	}
	
	.focus-content {
		position: absolute;
		bottom: 0;
		left: 0;
		width: 100%;
		padding: 40rpx;
	}
	
	.focus-tag {
		display: inline-block;
		padding: 8rpx 20rpx;
		background-color: #ff6b6b;
		color: #fff;
		font-size: 24rpx;
		border-radius: 6rpx;
		margin-bottom: 20rpx;
	}
	
	.focus-title {
		font-size: 40rpx;
		font-weight: bold;
		color: #fff;
		line-height: 1.4;
		margin-bottom: 15rpx;
	}
	
	.focus-meta {
		display: flex;
		align-items: center;
		font-size: 24rpx;
		color: rgba(255,255,255,0.8);
	}
	
	.dot {
		margin: 0 10rpx;
	}
	
	.featured-section {
		margin-bottom: 40rpx;
	}
	
	.section-title {
		padding: 0 40rpx;
		margin-bottom: 20rpx;
		display: flex;
		align-items: center;
	}
	
	.title-text {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-right: 20rpx;
	}
	
	.title-line {
		flex: 1;
		height: 2rpx;
		background-color: #eee;
	}
	
	.featured-scroll {
		white-space: nowrap;
		padding: 20rpx 30rpx;
	}
	
	.featured-card {
		display: inline-block;
		width: 300rpx;
		margin-right: 20rpx;
		border-radius: 20rpx;
		overflow: hidden;
		position: relative;
		background-color: #fff;
		box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.08);
	}
	
	.featured-image {
		width: 100%;
		height: 200rpx;
	}
	
	.featured-tag {
		position: absolute;
		top: 15rpx;
		left: 15rpx;
		background-color: rgba(0,0,0,0.7);
		color: #fff;
		font-size: 20rpx;
		padding: 6rpx 12rpx;
		border-radius: 6rpx;
	}
	
	.featured-title {
		font-size: 28rpx;
		font-weight: 500;
		color: #333;
		padding: 20rpx 20rpx 10rpx;
		line-height: 1.4;
		white-space: normal;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
	}
	
	.featured-source {
		padding: 0 20rpx 20rpx;
		font-size: 22rpx;
		color: #888;
	}
	.news-section {
		
	}
	
	.news-list {
		padding: 0 30rpx;
	}
	
	.news-item {
		display: flex;
		justify-content: space-between;
		padding: 30rpx;
		background-color: #fff;
		margin-bottom: 20rpx;
		border-radius: 20rpx;
		box-shadow: 0 2rpx 15rpx rgba(0,0,0,0.05);
	}
	
	.news-content {
		flex: 1;
		margin-right: 20rpx;
	}
	
	.news-top {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 15rpx;
	}
	
	.news-tag {
		font-size: 22rpx;
		color: #6c5ce7;
		padding: 4rpx 10rpx;
		background-color: rgba(108, 92, 231, 0.1);
		border-radius: 4rpx;
	}
	
	.news-time {
		font-size: 22rpx;
		color: #999;
	}
	
	.news-title {
		font-size: 32rpx;
		color: #333;
		font-weight: 500;
		line-height: 1.4;
		margin-bottom: 20rpx;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
	}
	
	.news-source {
		display: flex;
		align-items: center;
		font-size: 24rpx;
		color: #888;
	}
	
	.source-avatar {
		width: 36rpx;
		height: 36rpx;
		border-radius: 50%;
		overflow: hidden;
		margin-right: 10rpx;
	}
	
	.source-avatar image {
		width: 100%;
		height: 100%;
	}
	
	.news-image {
		width: 180rpx;
		height: 140rpx;
		border-radius: 12rpx;
		overflow: hidden;
		flex-shrink: 0;
	}
	
	.news-image image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}
	
	/* 加载更多 */
	.load-more {
		text-align: center;
		padding: 30rpx 0;
		color: #999;
		font-size: 26rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.loading-spinner {
		width: 30rpx;
		height: 30rpx;
		border: 2rpx solid #f3f3f3;
		border-top: 2rpx solid #666;
		border-radius: 50%;
		margin-right: 10rpx;
		animation: spin 1s linear infinite;
	}
	
	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}
	.fab-button {
		position: fixed;
		right: 40rpx;
		bottom: 140rpx;
		width: 90rpx;
		height: 90rpx;
		border-radius: 50%;
		background-color: #6c5ce7;
		display: flex;
		justify-content: center;
		align-items: center;
		box-shadow: 0 4rpx 20rpx rgba(108, 92, 231, 0.4);
		z-index: 10;
	}
	
	.category-flow ::-webkit-scrollbar,
	.featured-scroll ::-webkit-scrollbar,
	.content-scroll ::-webkit-scrollbar {
		display: none !important;
		width: 0 !important;
		height: 0 !important;
		background: transparent !important;
	}
</style>
